# -*- coding: utf-8 -*-
import sys

import qtawesome as qta
import PyQt5.uic
from PyQt5.QtWidgets import QApplication, QMainWindow, QDesktopWidget, QWidget, QDialog
from PyQt5 import uic

from global_data.glabal_data import GlobalData
from utils.dialog_utils import DialogUtils
from utils.file_utils import FileUtils
from utils.icloudp_log import IcloudpLog


class BaseWidget(QWidget):
    def __init__(self, title=None, ui_path=None, log_name="log", parent=None, app=None, rate = 0.6):
        super(BaseWidget, self).__init__()
        self.screenHeight = None
        self.screenWidth = None
        self.app = app
        self.ui = None
        self.ui_path = ui_path
        self.rate = rate

        self.title = title if title is not None else self.windowTitle()
        self.setWindowTitle(self.title)
        self.log_name = log_name
        self.log = IcloudpLog.get_logger(self.log_name)
        self.log.debug("初始化widget窗口")

        self.setWindowIcon(qta.icon(GlobalData.SYS_IMG))

        # 初始化窗口的其他属性，例如布局、菜单栏等
        self.init_ui()
        # 初始化大小
        self.init_size(self.rate)
        # 初始化事件
        self.init_events()
        # 初始化样式
        # self.init_style()

        # 初始化自定义的属性
        self.custom_init()

    def custom_init(self):
        # 自定义初始化
        pass

    def init_style(self):        
        self.setStyleSheet("""
                            .QWidget {border-width: 0px; border-style: none;}
                            .QStackedWidget {border-width: 0px; border-style: none;}
                            QFrame {border-width: 0; border-style: none;}
                            QGroupBox::title {line-height: 30px; margin-bottom: -10px; }
                            QLabel {font: 16px 宋体 ; color: #fff;}
                            QLineEdit {font: 16px 宋体 ; color: #fff;}
                            QPlainTextEdit {font: 16px 宋体 ; color: #fff; border-width: 1px; border-style: solid;}
                            QPushButton {font: 16px 宋体 ; color: #fff; height:25px; width:120px;}
                            QTextEdit {font: 16px 宋体 ; color: #fff; border-width: 1px; border-style: solid;}
                            QTextBrowser {font: 16px 宋体 ; color: #fff; }
                            QComboBox {font: 16px 宋体 ; color: #fff;}
                        """)

    def init_ui(self):
        self.log.debug("加载widget窗口ui")
        # 初始化界面的具体实现
        # self.ui, _ = uic.loadUiType(FileUtils.get_ui_path(self.ui_path), self)
        self.ui = uic.loadUi(FileUtils.get_ui_path(self.ui_path), self)
        # self.setCentralWidget(self.ui)

    def set_size(self, w, h):
        # 设置窗口大小
        self.setFixedSize(w, h)

    def init_size(self, rate):
        desktop = QDesktopWidget()
        self.screenWidth = desktop.screenGeometry().width() * rate
        self.screenHeight = desktop.screenGeometry().height() * rate
        self.resize(self.screenWidth, self.screenHeight)

    def init_events(self):
        self.log.debug("init_events=============")
        pass

    # 自定义事件===================================
    def closeEvent(self, event):
        # 在这里添加您想要在窗口关闭时执行的代码
        self.log.debug("[Widget]窗口正在关闭...")
        if DialogUtils.checkRes(DialogUtils.confirm("是否确认要关闭窗口？？？")):
            # 如果需要阻止关闭事件，可以设置event.ignore()，否则调用event.accept()
            if self.ui:
                self.ui.close()
            self.log.debug("接受关闭窗口事件")
            event.accept()  # 接受关闭事件
            self.close()
            self.destroy()
        else:
            self.log.debug("忽略关闭窗口事件")
            event.ignore()

    def exit(self, main_win, main_app):
        for widget in QApplication.topLevelWidgets():
            if isinstance(widget, QWidget) and widget != main_win:
                if widget.isHidden():  # 检查窗口是否已经被隐藏（即关闭）
                    continue;
                widget.close()
                main_app.topLevelWidgets().remove(widget)  # 从应用程序的顶级窗口列表中移除窗口
        main_win.close()
        main_app.quit()
        PyQt5.QtWidgets.qApp.quit
        sys.exit(0)
        QApplication.exit(0)  # 退出程序

    def showMaximized(self):
        # 当窗口最大化时执行的代码
        self.log.debug("Window was maximized")

    def showMinimized(self):
        # 当窗口最小化时执行的代码
        self.log.debug("Window was minimized")
        super(BaseWidget, self).showMinimized()

    def showNormal(self):
        # 当窗口恢复正常大小时执行的代码
        self.log.debug("Window was restored")
        super(BaseWidget, self).showNormal()

    def changeEvent(self, event):
        # 检查是否是最大化/最小化事件
        # self.log.debug(f"监测事件。。。。。。。。。。。。。。。")
        # if event.type() == event.WindowStateChange:
        #     if self.windowState() & self.isMaximized:
        #         self.showMaximized()
        #     elif self.windowState() & self.isMinimized:
        #         self.showMinimized()
        #     elif self.windowState() & self.Normal:
        #         self.showNormal()
        # QMainWindow.changeEvent(self, event)
        pass

    # 自定义方法 =================================================
    def center(self):
        # 窗口居中
        screen = QApplication.desktop().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2)

    # def show(self):
    #     print("show------------------------------")
    #     super(BaseWeight, self).show()
        
    def print_style(self, widget):
        style = widget.styleSheet()
        print(f"控件=【{widget.objectName()}】样式={style}")
 
    def set_default_by_hidden_value(self, cb, hidden_value):
        for i in range(cb.count()):
            if cb.itemData(i) == hidden_value:
                cb.setCurrentIndex(i)
                break

    def get_combobox_hidden_value(self, cb):
        return cb.itemData(cb.currentIndex())

class BaseMainWindow(QMainWindow, BaseWidget):
    def __init__(self, title=None, ui_path=None, log_name=None, parent=None, app=None, rate = 0.6):
        super(BaseMainWindow, self).__init__(title = title, ui_path = ui_path, log_name = log_name, parent = parent, app = app, rate = rate)
        self.setWindowTitle(self.title)
        self.log.debug("初始化main窗口")

    # def init_ui(self):
    #     self.log.debug("载入main窗口ui")
    #     # 初始化界面的具体实现
    #     # self.ui, _ = uic.loadUiType(FileUtils.get_ui_path(self.ui_path), self)
    #     self.ui = uic.loadUi(FileUtils.get_ui_path(self.ui_path), self)

    # def closeEvent(self, event):
    #     # 在这里添加您想要在窗口关闭时执行的代码
    #     self.log.debug("[MainWindow]窗口正在关闭...")
    #     if DialogUtils.checkRes(DialogUtils.confirm("是否确认要关闭窗口？？？")):
    #         if self.ui:
    #             self.ui.close()
    #         # self.close()
    #         self.log.debug("接受关闭窗口事件")
    #         # 如果需要阻止关闭事件，可以设置event.ignore()，否则调用event.accept()
    #         event.accept()  # 接受关闭事件
    #     else:
    #         self.log.debug("忽略关闭窗口事件")
    #         event.ignore()


class BaseDialog(QDialog, BaseWidget):
    def __init__(self, title=None, ui_path=None, log_name=None, parent=None, rate = 0.6):
        super(BaseDialog, self).__init__(title, ui_path, log_name, parent, rate = rate)
        self.setWindowTitle(self.title)
        self.log.debug("初始化main窗口")

    # def init_ui(self):
    #     self.log.debug("载入dialog窗口ui")

    # 自定义事件===================================
    def closeEvent(self, event):
        # 在这里添加您想要在窗口关闭时执行的代码
        self.log.debug("[Dialog]窗口正在关闭...")
        if DialogUtils.checkRes(DialogUtils.confirm("是否确认要关闭窗口？？？")):
            # 如果需要阻止关闭事件，可以设置event.ignore()，否则调用event.accept()
            self.log.debug("接受关闭窗口事件")
            self.accept()
            # self.destroy()
            event.accept()
        else:
            self.log.debug("忽略关闭窗口事件")
            self.reject()
            event.ignore()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = BaseMainWindow()
    window.center()
    window.show()
    sys.exit(app.exec_())

    # self.exec()  启动模态
    # self.win_test = WindowTest()
    # zt = self.win_test.exec()
    # # 点击了确定按钮
    # if zt:
    #     zt1 = True
    # # 点击了取消按钮或关闭了弹窗
    # else:
    #     zt1 = False
    # print(zt)
    # # 获取短信框中的短信内容
    # content = self.win_test.txt_dialog_res.text()
    # # txt_dialog_res
    # print(content)